<template>
  <view class="users">
    <view class="header">
      <text class="title">用户管理</text>
    </view>

    <view class="search-bar">
      <input class="search-input" v-model="searchKeyword" placeholder="搜索用户手机号或昵称" @input="searchUsers" />
    </view>

    <view class="user-list">
      <view v-for="user in users" :key="user.id" class="user-item">
        <view class="user-avatar">
          <image v-if="user.avatar" :src="user.avatar" class="avatar-img" />
          <text v-else class="avatar-text">{{ user.nickname ? user.nickname.charAt(0) : '用' }}</text>
        </view>

        <view class="user-info">
          <text class="user-name">{{ user.nickname || '未设置昵称' }}</text>
          <text class="user-phone">{{ user.phone || '未绑定手机' }}</text>
          <text class="user-points">积分: {{ user.points }}</text>
          <text class="user-level">等级: {{ user.memberLevel }}</text>
        </view>

        <view class="user-status">
          <text class="status-badge" :class="user.status === 1 ? 'status-active' : 'status-inactive'">
            {{ user.status === 1 ? '正常' : '禁用' }}
          </text>
          <text class="user-role">{{ user.role === 'admin' ? '管理员' : '普通用户' }}</text>
        </view>

        <view class="user-actions">
          <button class="btn-edit" @click="editUser(user)">编辑</button>
          <button class="btn-toggle" :class="user.status === 1 ? 'btn-disable' : 'btn-enable'"
            @click="toggleUserStatus(user)">
            {{ user.status === 1 ? '禁用' : '启用' }}
          </button>
        </view>
      </view>
    </view>

    <view class="pagination">
      <button class="page-btn" :disabled="currentPage <= 1" @click="loadUsers(currentPage - 1)">
        上一页
      </button>
      <text class="page-info">{{ currentPage }} / {{ totalPages }}</text>
      <button class="page-btn" :disabled="currentPage >= totalPages" @click="loadUsers(currentPage + 1)">
        下一页
      </button>
    </view>

    <!-- 编辑用户弹窗 -->
    <view v-if="editingUser" class="modal-overlay" @click="closeEditModal">
      <view class="modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">编辑用户</text>
          <text class="modal-close" @click="closeEditModal">×</text>
        </view>
        <view class="modal-body">
          <view class="form-group">
            <text class="form-label">昵称</text>
            <input class="form-input" v-model="userForm.nickname" placeholder="请输入昵称" />
          </view>
          <view class="form-group">
            <text class="form-label">手机号</text>
            <input class="form-input" v-model="userForm.phone" placeholder="请输入手机号" />
          </view>
          <view class="form-group">
            <text class="form-label">积分</text>
            <input class="form-input" type="number" v-model="userForm.points" placeholder="请输入积分" />
          </view>
          <view class="form-group">
            <text class="form-label">会员等级</text>
            <picker :value="memberLevelIndex" :range="memberLevels" @change="onMemberLevelChange">
              <view class="picker-view">{{ memberLevels[memberLevelIndex] }}</view>
            </picker>
          </view>
          <view class="form-group">
            <text class="form-label">用户角色</text>
            <picker :value="roleIndex" :range="roles" @change="onRoleChange">
              <view class="picker-view">{{ roles[roleIndex] }}</view>
            </picker>
          </view>
          <view class="form-group">
            <text class="form-label">状态</text>
            <picker :value="statusIndex" :range="statusOptions" @change="onStatusChange">
              <view class="picker-view">{{ statusOptions[statusIndex] }}</view>
            </picker>
          </view>
        </view>
        <view class="modal-footer">
          <button class="btn-cancel" @click="closeEditModal">取消</button>
          <button class="btn-confirm" @click="saveUser">保存</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      users: [],
      searchKeyword: '',
      currentPage: 1,
      totalPages: 1,
      pageSize: 10,
      editingUser: null,
      userForm: {
        nickname: '',
        phone: '',
        points: 0,
        memberLevel: 'bronze',
        role: 'user',
        status: 1
      },
      memberLevels: ['bronze', 'silver', 'gold', 'platinum'],
      memberLevelIndex: 0,
      roles: ['普通用户', '管理员'],
      roleIndex: 0,
      statusOptions: ['禁用', '正常'],
      statusIndex: 1
    }
  },

  onLoad() {
    this.loadUsers()
  },

  methods: {
    async loadUsers(page = 1) {
      try {
        const token = uni.getStorageSync('token')
        if (!token) {
          uni.navigateTo({ url: '/pages/auth/login' })
          return
        }

        const { getUsers } = require('@/api/admin')
        const res = await getUsers({
          page: page,
          limit: this.pageSize,
          search: this.searchKeyword
        })

        console.log('Users API响应:', res)

        if (res && res.success) {
          this.users = res.data.users || []
          this.currentPage = res.data.currentPage || 1
          this.totalPages = res.data.totalPages || 1
        }
      } catch (error) {
        console.error('加载用户失败:', error)
        uni.showToast({
          title: '加载用户失败',
          icon: 'none'
        })
      }
    },

    searchUsers() {
      // 防抖搜索
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.loadUsers(1)
      }, 500)
    },

    editUser(user) {
      this.editingUser = user
      this.userForm = {
        nickname: user.nickname || '',
        phone: user.phone || '',
        points: user.points || 0,
        memberLevel: user.memberLevel || 'bronze',
        role: user.role || 'user',
        status: user.status || 1
      }

      // 设置选择器索引
      this.memberLevelIndex = this.memberLevels.indexOf(this.userForm.memberLevel)
      this.roleIndex = this.userForm.role === 'admin' ? 1 : 0
      this.statusIndex = this.userForm.status === 1 ? 1 : 0
    },

    async toggleUserStatus(user) {
      const action = user.status === 1 ? '禁用' : '启用'
      uni.showModal({
        title: `确认${action}`,
        content: `确定要${action}用户 ${user.nickname || user.phone} 吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const token = uni.getStorageSync('token')
              const { updateUserStatus } = require('@/api/admin')
              const updateRes = await updateUserStatus(user.id, {
                status: user.status === 1 ? 0 : 1
              })

              if (updateRes && updateRes.success) {
                uni.showToast({ title: `${action}成功` })
                this.loadUsers(this.currentPage)
              }
            } catch (error) {
              uni.showToast({ title: `${action}失败`, icon: 'none' })
            }
          }
        }
      })
    },

    closeEditModal() {
      this.editingUser = null
      this.userForm = {
        nickname: '',
        phone: '',
        points: 0,
        memberLevel: 'bronze',
        role: 'user',
        status: 1
      }
    },

    async saveUser() {
      try {
        const token = uni.getStorageSync('token')
        const { updateUser } = require('@/api/admin')
        const res = await updateUser(this.editingUser.id, this.userForm)

        if (res && res.success) {
          uni.showToast({ title: '保存成功' })
          this.closeEditModal()
          this.loadUsers(this.currentPage)
        }
      } catch (error) {
        uni.showToast({ title: '保存失败', icon: 'none' })
      }
    },

    onMemberLevelChange(e) {
      this.memberLevelIndex = e.detail.value
      this.userForm.memberLevel = this.memberLevels[e.detail.value]
    },

    onRoleChange(e) {
      this.roleIndex = e.detail.value
      this.userForm.role = e.detail.value === 1 ? 'admin' : 'user'
    },

    onStatusChange(e) {
      this.statusIndex = e.detail.value
      this.userForm.status = e.detail.value === 1 ? 1 : 0
    }
  }
}
</script>

<style scoped>
.users {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.search-bar {
  margin-bottom: 30rpx;
}

.search-input {
  width: 100%;
  padding: 20rpx;
  background: white;
  border-radius: 12rpx;
  font-size: 28rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.user-list {
  background: white;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 30rpx;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.user-item:last-child {
  border-bottom: none;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #007bff;
  color: white;
}

.avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.avatar-text {
  font-size: 32rpx;
  font-weight: bold;
}

.user-info {
  flex: 1;
  margin-right: 20rpx;
}

.user-name {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.user-phone {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.user-points,
.user-level {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-bottom: 4rpx;
}

.user-status {
  margin-right: 20rpx;
  text-align: center;
}

.status-badge {
  display: block;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: white;
  margin-bottom: 8rpx;
}

.status-active {
  background-color: #28a745;
}

.status-inactive {
  background-color: #dc3545;
}

.user-role {
  font-size: 24rpx;
  color: #666;
}

.user-actions {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.btn-edit {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}

.btn-disable {
  background-color: #dc3545;
  color: white;
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}

.btn-enable {
  background-color: #28a745;
  color: white;
  border: none;
  padding: 12rpx 24rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30rpx;
  padding: 30rpx;
}

.page-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.page-btn:disabled {
  background-color: #ccc;
}

.page-info {
  font-size: 28rpx;
  color: #666;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.modal-close {
  font-size: 48rpx;
  color: #999;
}

.modal-body {
  padding: 30rpx;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 12rpx;
}

.form-input {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.picker-view {
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #f8f9fa;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #eee;
}

.btn-cancel {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.btn-confirm {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 16rpx 32rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}
</style>